package cn.zxyh.config;


import cn.zxyh.pojo.User;
import com.alibaba.fastjson.parser.ParserConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.concurrent.TimeUnit;

@Configuration
public class RedisConfig {
    @Autowired
    private RedisConnectionFactory factory;

    /**
     * 使用fastjson序列化
     *
     * @return RedisSerializer
     */
    @Bean
    public RedisSerializer fastJson2JsonRedisSerializer() {
        ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        return new FastJson2JsonRedisSerializer<>(Object.class);
    }

    /**
     * 生成redisTemplate注入fastjsion序列化器
     *
     * @param factory redis连接工厂
     * @return redisTemplate
     */
    @SuppressWarnings("unchecked")
    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    @Primary
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(fastJson2JsonRedisSerializer());
        redisTemplate.setHashValueSerializer(fastJson2JsonRedisSerializer());
        redisTemplate.afterPropertiesSet();
        // 预先写入一个用户
        User user = new User();
        user.setId(123);
        user.setCardNumber("12345678");
        user.setPassword("523d");
        user.setStatus(0);
        user.setUsername("baiman");
        redisTemplate.opsForValue().set("12345", user, 30, TimeUnit.MINUTES);
        return redisTemplate;
    }
}
